package de.bloxel.world;

import com.jme3.bounding.BoundingBox;
import com.jme3.math.Vector3f;

import de.bloxel.core.BloxelFactory.BloxelType;

/**
 * @author andreas
 * @since 0.1.0
 */
public class FillTerrainLoader implements TerrainLoader {

  /**
   * Each {@link TerrainElement} will have this size in x, y and z direction from the element center position.
   */
  private final Vector3f elementSize;

  /**
   * Use default element size of 0.5f in each direction.
   */
  public FillTerrainLoader() {
    this(Vector3f.UNIT_XYZ.mult(0.5f));
  }

  /**
   * @param theElementSize
   *          to use, each {@link TerrainElement} will have this size in x,y and z direction from the element center
   *          position
   */
  public FillTerrainLoader(final Vector3f theElementSize) {
    elementSize = theElementSize;
  }

  @Override
  public void fill(final TerrainChunk theTerrainChunk) {
    final BoundingBox bv = theTerrainChunk.getBoundingBox();
    final float xExtent = bv.getXExtent();
    final float yExtent = bv.getYExtent();
    final float zExtent = bv.getZExtent();
    final float startx = -xExtent + getElementSize().x;
    final float endx = xExtent - getElementSize().x;
    final float starty = -yExtent + getElementSize().y;
    final float endy = yExtent - getElementSize().y;
    final float startz = -zExtent + getElementSize().z;
    final float endz = zExtent - getElementSize().z;
    final float stepx = getElementSize().x * 2;
    final float stepz = getElementSize().z * 2;
    final float stepy = getElementSize().y * 2;
    for (float x = startx; x <= endx; x += stepx) {
      for (float y = starty; y <= endy; y += stepy) {
        for (float z = startz; z <= endz; z += stepz) {
          final Vector3f elementCenter = new Vector3f(x, y, z).add(bv.getCenter());
          final TerrainElement terrainElement = new TerrainElement(elementCenter, getElementSize(), BloxelType.GRASS);
          theTerrainChunk.addTerrainElement(terrainElement);
        }
      }
    }
  }

  @Override
  public Vector3f getElementSize() {
    return elementSize;
  }
}